package com.example.lin.generate;

import com.example.lin.util.EddTimeUtils;
import com.example.lin.util.ExportUtil;
import com.example.lin.util.ImportUtil;
import com.example.lin.vo.EddHolidayVO;
import com.example.lin.vo.EddImportUtilVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @className: GenerateEddImportInfo
 * @description: 生成 EDD 导入工具信息
 * @author: Lin.Gu
 * @date: 2025/4/28
 */
public class GenerateEddImportInfo {

    public static Map<String, List<EddHolidayVO>> eddHolidayMap = new LinkedHashMap<>();
    public static Map<String, EddImportUtilVO> eddImportUtilMap = new LinkedHashMap<>();


    /**
     * 根据表格 生成导入 跑批 EDD数据
     * sheet1标头： 项目	产品	始发地	目的地	供应商编码	供应商服务编码 时差 配置ID	  CD天数 节点顺序 jvCode	BD天数
     * sheet2标头： 国家 开始日期	结束日期	时区 名称
     *
     * @param args 命令行参数
     * @throws Exception 抛出异常
     */
    public static void main(String[] args) throws Exception {
        String filePath = "D:\\资料\\SPK\\常用模板\\生成EDD跑批数据导入案例.xlsx";
        //TODO: EDD节假日sheet信息
        int sheet = 1;
        List<List<Object>> holidayList = ImportUtil.readExcelToList(filePath, sheet);
        if (CollectionUtils.isNotEmpty(holidayList)) {
            for (List<Object> objects : holidayList) {
                String countryCode = (String) objects.get(0);
                String startDate = (String) objects.get(1);
                String endDate = (String) objects.get(2);
                String holidayZone = (String) objects.get(3);
                String holidayName = (String) objects.get(4);
                List<EddHolidayVO> eddHolidayVOS = Optional.ofNullable(eddHolidayMap.get(countryCode)).orElse(new ArrayList<>());
                String dateFormat = EddTimeUtils.DATE_FORMAT;
                eddHolidayVOS.add(new EddHolidayVO(countryCode,
                        EddTimeUtils.strToDate(startDate, dateFormat),
                        EddTimeUtils.strToDate(endDate, dateFormat),
                        holidayZone,
                        holidayName));
                eddHolidayMap.put(countryCode, eddHolidayVOS);
            }
            System.out.println("初始化假期完成:" + eddHolidayMap.size());
        }

        //EDD配置读取
        List<Object[]> data = new ArrayList<>();
        data.add(new Object[]{"*项目", "*产品服务", "供应商", "供应商服务", "*始发地", "*目的地", "*JV Code", "*初始日期", "*预计日期1", "*预计日期2", "*预计日期3"});
        //TODO: EDD配置sheet信息
        sheet = 0;
        List<List<Object>> eddList = ImportUtil.readExcelToList(filePath, sheet);
        if (CollectionUtils.isNotEmpty(eddList)) {
            for (List<Object> objects : eddList) {
                String projectCode = (String) objects.get(0);
                String serviceId = (String) objects.get(1);
                String origional = (String) objects.get(2);
                String destination = (String) objects.get(3);
                String vendorCode = (String) objects.get(4);
                String vendorServiceCode = (String) objects.get(5);
                String timeDifference = (String) objects.get(6);
                String nodeNum = (String) objects.get(7);
                String jvIndex = (String) objects.get(8);
                String jvCode = (String) objects.get(9);
                String slaAging = (String) objects.get(10);


                String repeatTheCheck = projectCode + serviceId + origional + destination + vendorCode + vendorServiceCode + jvCode + timeDifference;
                EddImportUtilVO eddImportUtilVO = Optional.ofNullable(eddImportUtilMap.get(repeatTheCheck)).orElse(new EddImportUtilVO());
                if (StringUtils.isEmpty(eddImportUtilVO.getProjectCode())) {
                    eddImportUtilVO.setProjectCode(projectCode);
                    eddImportUtilVO.setServiceCode(serviceId);
                    eddImportUtilVO.setOriginal(origional);
                    eddImportUtilVO.setDestination(destination);
                    eddImportUtilVO.setVendorCode(vendorCode);
                    eddImportUtilVO.setVendorServiceCode(vendorServiceCode);
                    eddImportUtilVO.setJvCode(jvCode);
                    eddImportUtilVO.setTimeDifference(Integer.valueOf(timeDifference));
                }
                if (nodeNum.equals("1")) {
                    eddImportUtilVO.setJvCodeOne(Integer.valueOf(slaAging));
                }
                if (nodeNum.equals("2")) {
                    eddImportUtilVO.setJvCodeTwo(Integer.valueOf(slaAging));
                }
                if (nodeNum.equals("3")) {
                    eddImportUtilVO.setJvCodeThree(Integer.valueOf(slaAging));
                }
                eddImportUtilMap.put(repeatTheCheck, eddImportUtilVO);
            }
            System.out.println("eddImportUtilMap处理完成:" + eddImportUtilMap.size());
        }

        //TODO: 初始日期
        String initDate = "2025-07-02 00:00:00";

        for (EddImportUtilVO value : eddImportUtilMap.values()) {
            //计算EDD预计日期
            String dateOne = "", dateTwo = "", dateThree = "";
            //节假日  A-scan 节点 FE/DH 目的国家为空 默认用US 如果开启了随机国家 那这个就不准确了
            String destination = StringUtils.isEmpty(value.getDestination()) ? "US" : value.getDestination();
            List<EddHolidayVO> eddHolidayVOS = eddHolidayMap.get(destination);
            //时差
            Integer timeDifference = value.getTimeDifference();

            if (Objects.nonNull(value.getJvCodeOne())) {
                Date estimatedDeliveryDate = EddTimeUtils.strToDate(initDate, EddTimeUtils.DATE_TIME_FORMAT);
                Date orderSlaAgingDate = getOrderSlaAgingDate(estimatedDeliveryDate, eddHolidayVOS, value.getJvCodeOne(), timeDifference);
                value.setJvCodeOneStartTime(orderSlaAgingDate);
                dateOne = EddTimeUtils.convert(orderSlaAgingDate, EddTimeUtils.DATE_TIME_FORMAT);
            }
            if (Objects.nonNull(value.getJvCodeTwo())) {
                Date orderSlaAgingDate = getOrderSlaAgingDate(value.getJvCodeOneStartTime(), eddHolidayVOS, value.getJvCodeTwo(), timeDifference);
                value.setJvCodeTwoStartTime(orderSlaAgingDate);
                dateTwo = EddTimeUtils.convert(orderSlaAgingDate, EddTimeUtils.DATE_TIME_FORMAT);
            }

            if (Objects.nonNull(value.getJvCodeThree())) {
                Date orderSlaAgingDate = getOrderSlaAgingDate(value.getJvCodeTwoStartTime(), eddHolidayVOS, value.getJvCodeThree(), timeDifference);
                value.setJvCodeThreeStartTime(orderSlaAgingDate);
                dateThree = EddTimeUtils.convert(orderSlaAgingDate, EddTimeUtils.DATE_TIME_FORMAT);
            }

            data.add(new Object[]{value.getProjectCode(), value.getServiceCode(),
                    value.getVendorCode(), value.getVendorServiceCode(),
                    value.getOriginal(), value.getDestination(),
                    value.getJvCode(),
                    initDate, dateOne, dateTwo, dateThree});
        }

        if (data.size() > 1) {
            System.out.println("总条数信息:" + data.size());
            ExportUtil.exportTheFile("EDD跑批工具导入数据信息" + sheet, data);
        }
    }


    public static Date getOrderSlaAgingDate(Date estimatedDeliveryDate, List<EddHolidayVO> holidayList, Integer
            slaAging, Integer timeDifference) {
        try {

            Calendar instance = Calendar.getInstance();
            instance.setTime(estimatedDeliveryDate);

            // 计算初始结果日期
            Date resultDate = EddTimeUtils.addDateByWorkDay(instance, slaAging).getTime();

            if (CollectionUtils.isNotEmpty(holidayList)) {

                // 时差为0  那就取节假日的时差信息
                if (timeDifference == 0) {
                    EddHolidayVO eddHolidayVO = holidayList.get(0);
                    String timeZone = !StringUtils.isEmpty(eddHolidayVO.getHolidayZone()) ? eddHolidayVO.getHolidayZone() : "0";
                    timeDifference = EddTimeUtils.getTimeZone(timeZone);
                }
                // 缓存东八区时间差
                long timeZoneOffsetInMillis = timeDifference * 60 * 60 * 1000;

                // 定义时间范围
                Date startTime = EddTimeUtils.getStartDatetime(estimatedDeliveryDate);
                Date endTime = EddTimeUtils.getEndDatetime(resultDate);

                // 计算假日影响
                Long totalHolidays = EddTimeUtils.calculateTotalHolidays(holidayList, startTime, endTime, timeZoneOffsetInMillis);

                if (totalHolidays > 0) {
                    // 累加假期天数
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(resultDate);
                    resultDate = EddTimeUtils.addDateByWorkDay(calendar, totalHolidays.intValue()).getTime();
                }
            }
            return resultDate;
        } catch (Exception e) {
            throw new RuntimeException("getOrderSlaAgingDate异常:" + e.getMessage());
        }
    }


}
